package model.factories.environment;

import java.awt.Image;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;
import model.commands.environment.ChangeBackgroundImageCommand;
import model.factories.CommandFactory;


/**
 * A factory used to create ChangeBackgroundImageCommand objects.
 * 
 * @author Erick Gonzalez
 */
public class ChangeBackgroundImageCommandFactory extends CommandFactory {
        
    private static final String CHANGE_BACKGROUND_IMG_PATTERN = "ChangeBackgroundImagePattern";
    private final Pattern myChangeBGPattern = Pattern.
            compile(getInterpreter().getLanguage().getString(CHANGE_BACKGROUND_IMG_PATTERN));
    private final String myRemoveBGKeyword = Pattern.compile(getInterpreter().
                     getLanguage().getString(CHANGE_BACKGROUND_IMG_PATTERN)).
                     toString();

    /**
     * 
     * @param interpreter an interpreter
     */
    public ChangeBackgroundImageCommandFactory (Interpreter interpreter) {
        super(interpreter);
    }

    @Override
    public Pattern patternToMatch () {
        return myChangeBGPattern;
    }

    @Override
    public Command createCommand (Scanner commandReader,
                                  Map<String, Integer> variables) throws SyntaxErrorException {
        // read command keyword
        String commandKeyword = commandReader.next();

        StringBuilder imageFilePath = new StringBuilder();
        while (commandReader.hasNext()) {
            imageFilePath.append(commandReader.next() + " ");
        }
        Image ii = (new ImageIcon(imageFilePath.toString().trim())).getImage();

        if (commandKeyword.equals(myRemoveBGKeyword)) {
            ii = null;
        }

        return new ChangeBackgroundImageCommand(ii);
    }
}
